package org.nettyServer.connectionManage;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j
public class ConnectionManage {
    /**
     * 用于存放已经注册的连接
     */
    static CopyOnWriteArrayList<ClientInfo> clientInfos= new CopyOnWriteArrayList<>();

    /**
     * 用于存放未注册的连接
     */
    static CopyOnWriteArrayList<NotRegisterClientInfo> notRegisterClientInfos= new CopyOnWriteArrayList<>();



    public static List<NotRegisterClientInfo> getNotRegisterClientInfos(){
        return notRegisterClientInfos;
    }

    public static NotRegisterClientInfo getClientInfoFromNotRegisterClient(Channel channel){
        return notRegisterClientInfos
               .stream()
               .filter(clientInfo -> clientInfo.getChannel().equals(channel))
               .findFirst()
               .orElse(null);
    }

    public static void addNotRegisterClientInfo(NotRegisterClientInfo notRegisterClientInfo){
        notRegisterClientInfos.add(notRegisterClientInfo);
    }
    public static void removeNotRegisterClientInfo(Channel channel){
        notRegisterClientInfos
                .stream()
                .filter(notRegisterClientInfo -> notRegisterClientInfo.getChannel().equals(channel))
                .findFirst()
                .ifPresentOrElse(notRegisterClientInfo -> {
                    //如果未注册连接中找到了该连接，说明该连接未注册过，直接从未注册连接中移除
                    notRegisterClientInfos.remove(notRegisterClientInfo);
                    log.info("[未注册连接管理]---->移除连接");
                },()->{
                    //如果未注册连接中没有找到该连接，说明该连接已经注册过了，直接从已注册连接中移除
                    removeClientInfo(channel);
                });
    }


    public static List<ClientInfo> getClientInfos(){
        return clientInfos;
    }
    public static ClientInfo getClientInfo(Channel channel){
        return clientInfos
               .stream()
               .filter(clientInfo -> clientInfo.getChannel().equals(channel))
               .findFirst()
               .orElse(null);
    }

    public static void addClientInfo(ClientInfo clientInfo){
        clientInfos.add(clientInfo);
    }
    public static void removeClientInfo(Channel channel){
        clientInfos
                .stream()
                .filter(clientInfo -> clientInfo.getChannel().equals(channel)).findFirst()
                .ifPresentOrElse(clientInfo -> {
                    clientInfos.remove(clientInfo);
                    log.info("[已登录连接管理]---->移除连接");
                },()->log.info("[已登录连接管理]---->未找到该连接"));
    }
}
